<?php
namespace app\controller;



use Illuminate\Database\Eloquent\Model;
use support\Db;
use support\Request;

class Index
{
    public function index(Request $request)
    {
        return response('2222');
    }

    public function view(Request $request)
    {
        return view('index/view', ['name' => 'webman']);
    }

    public function json(Request $request)
    {
        $res = Db::table('user')->get();

        return json(['code' => 0, 'msg' =>$res]);
    }
    public function test(Request $request)
    {
        $res = DB::table('user')->get();
        //var_dump($res);
        //return json(['code' => 0, 'msg' =>$res]);
    }
    public function  mqtt_back(Request $request){
        try{
            $data = $request->input('data');

            //file_put_contents("/www/wwwroot/webman/runtime/".date("Y-m-d").".log",date("H:i:s").$data."\r\n",FILE_APPEND);
            //$data = '{"data":"{\"sg\":21,\"data\":{\"sta\":1,\"deviceName\":\"D863644074533622\",\"mac_type\":\"F002\",\"ver\":\"1.0.1\",\"mec\":\"0xAA1092010303060001000002000000006C9C\"}}"}';
             //$data = '{"sg":21,"data":{"tm":0,"deviceName":"W863488058971188","sta":0,"ver":1,"rn":0},"type":"000307"}';
             $data = '{"sg":20,"online":1,"pro_ver":"1.1.2","type":"000304","Soft":3,"data":{"MecDat":"0x0001002D0C"},"deviceName":"D863488058973317"}';

            if(!$data){
                return false;
            }
            //$data = '{"data":{"sta":2,"tm":69,"rn":1},"type":"000305","deviceName":"C_K_W867435053383782","sg":25}';
            $data_arr=json_decode($data,true);

            if(array_key_exists("DEC_ID",$data_arr)){//设备IEMI码
                DB::table('device')->where('mqtt_name',$data_arr['deviceName'])->update(['dev_id'=>$data_arr['DEC_ID']]);

                return true;
            }
            if(array_key_exists("SIM",$data_arr)){ //电话卡sim卡号
                DB::table('device')->where('mqtt_name',$data_arr['deviceName'])->update(['dev_sim'=>$data_arr['SIM']]);

                return true;
            }


            if(!isset($data_arr['data'])){
                return false;
            }

            $data = $data_arr['data'];


            //判断json串钟是否包含deviceName
            if(!array_key_exists("deviceName",$data) && !array_key_exists("deviceName",$data_arr)){
                //无效消息丢弃
                return false;
            }

            if(array_key_exists("deviceName",$data_arr)){
                $deviceName = $data_arr['deviceName'];
            }else{
                $deviceName = $data['deviceName'];
            }

            //设备名称查询exile全局设备是否存在
            $device = DB::table('device')->where('mqtt_name',$deviceName)->first();

            $device = (array)$device;
            //   file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/zqxx.log",$deviceName."\r\n",FILE_APPEND);


            //判断mqtt协议
            if(empty($device)){
                //设备不存在，需要注册设备
                $this->RegisterDevice($data_arr);
            }else{

                //设备已经存在,则更新设备信息
                if(array_key_exists("mac_type",$data)){

                    switch ($data['mac_type']){

                        case 'F002'://kb烘干机4G

                            $this->handleDryer4G($data_arr,$device);
                            break;
                        case 'F001'://kb洗衣机4G

                            $this->handleKbWasher4G($data_arr,$device);
                            break;
                        default:
                            break;
                    }
                }else{
                    //没有传type的情况
                }

                if(array_key_exists("type",$data_arr)){

                    switch ($data_arr['type']){

                        case '000304'://kb烘干机4G

                            $this->handleDryer4G1($data_arr,$device);
                            break;
                        case '000305'://kb洗衣机4G

                            // $this->handleKbWasher4G1($data_arr,$device);
                            break;
                        case '000307'://新kb洗衣机4G

                            $this->handleNewKbWasher4G($data_arr,$device);
                            break;
                        default:
                    }
                }

            }

            return true;
        }catch (\Exception $e){
            echo $e->getMessage().$e->getLine();
            //file_put_contents("/www/wwwroot/webman/runtime/exile.log", date('Y-m-d H:i:s'). ' '. $e->getMessage(). ' in '. $e->getFile(). ' '. $e->getLine()."\r\n",FILE_APPEND);

            return false;
        }

    }

    private function  RegisterDevice($data_arr){

        $insert=[];
        $data = $data_arr['data'];
        //阿里云消息返回正常
//        echo "<pre>";
//        var_dump($data_arr);die;

        if(array_key_exists("mac_type",$data)){
            if($data['mac_type']=='F001')//洗衣机
                $insert['dev_type']=28;
            if($data['mac_type']=='F002') //烘干机
                $insert['dev_type']=29;
        }

        if(array_key_exists("type",$data_arr)){
            if($data_arr['type']=='000307')//洗衣机
                $insert['dev_type']=28;

            if($data_arr['type']=='000304'){//烘干机
                $insert['dev_type']=26;
                $insert['dev_tp']=7;
                $data['deviceName'] = $data_arr['deviceName'];
            }

        }

        $device = DB::table('device')->where('mqtt_name','like','%'.$data['deviceName'])->first();

        if($device){

            DB::table('device')->where('id',$device->id)->update(['dev_simid'=>$data['deviceName'],'mqtt_name'=>$data['deviceName'],'dev_type'=>$insert['dev_type']]);

            return;

        }
        if(array_key_exists("sta",$data)){
            if($data['sta']==0){
                $insert['ins_gz']=2;
                $insert['dev_status_name']="通讯异常";
            }
        }

        // $MecDat_arr=$this->getByateArray($data['mec'],2);

        //8洗衣模式	9洗衣状态	10故障状态	11剩余时间
        //ins_gz 1.工作 2设备异常 3空闲中4离线'
//        $insert['ins_gz']=2;
//        $insert['dev_status_name']='设备异常';//设备状态名称
//        if($MecDat_arr[9]==1){
//            $insert['ins_gz']=3;
//            $insert['dev_status_name']="空闲";
//        }
//        if($MecDat_arr[9]==2){
//            $insert['ins_gz']=1;
//            $insert['dev_status_name']="工作中";
//        }



        $insert['mqtt_name']=$data['deviceName'];
        $insert['dev_simid']=$data['deviceName'];
        $insert['protocol_type']=1;//mqtt协议

        $insert['create_time']=time();//设备创建时间
        if(array_key_exists("sg",$data_arr)){
            $insert['signal']=$data_arr['sg'];
        }
        //插入设备信息
        DB::table('device')->insert($insert);

        sleep(2);

        $this->publish('pro-50001',$data['deviceName'],1);
        $this->publish('pro-50002',$data['deviceName'],1);
        // file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/ddxxx.log",json_encode($insert)."\r\n",FILE_APPEND);


    }


    public function  handleDryer4G($data_arr,$device){

        //step1:添加日志信息
        $this->addLog($data_arr,$device);
        //step2:解析上报数据信息
        $update=[];
        $update["sum_line"]=2;//烘干机模式
        //获取阿里云设备注册名称
        $deviceName=$data_arr['data']["deviceName"];

        // $device= DB::table("device")->where("mqtt_name",$deviceName)->first();

        if(!$device){
            return ;//设备信息不存在就不用玩了
        }

        if(array_key_exists("ver",$data_arr['data'])){
            $update['ver']=$data_arr['data']['ver'];
        }

        //查询公用的一张物联网卡洗衣机是否在线
        DB::table("device")->where(["dev_sim"=>$device['dev_sim'],"dev_tp"=>8])->update(["ins_gz"=>4,"dev_status_name"=>"设备离线"]);


        if(array_key_exists("sg",$data_arr)){
            $update["signal"]=$data_arr['sg']."/".date("Y-m-d H:i:s");
        }
        if(array_key_exists("data",$data_arr)){
            $receive_data=$data_arr["data"];

            if(!is_array($receive_data)){
                $receive_data=json_decode($receive_data,true);
            }
            if(array_key_exists("mec",$receive_data)){
                $MecDat=$receive_data["mec"];
                $MecDat_arr=$this->getByateArray($MecDat,2);
                if(strlen($MecDat)!=38||$MecDat_arr[0]!="0x"){
                    if(array_key_exists("sta",$receive_data)){
                        if($receive_data['sta']==0){
                            $update['ins_gz']=4;
                            $update['dev_status_name']="通讯异常";
                        }

                    }
                    $update['update_time']=time();


                    DB::table("device")->where(["mqtt_name"=>$deviceName])->update($update);
                    return ;
                }
                //8洗衣模式	9洗衣状态	10故障状态	11剩余时间
                $status1 = $MecDat_arr[8];//洗衣模式  1烘干程序
                $status2 = $MecDat_arr[9];//洗衣状态 0	洗衣机占用 1	空闲  7异常  9烘干中
                $status3 = $MecDat_arr[10];//故障状态 0无故障    4门开
                $tm = $MecDat_arr[11];//剩余时间


                if($status2 == 9){
                    $order= DB::table("order")->where(["id"=>$device["order_id"]])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==1){
                            //确保当前订单已经付款成功过,设备成功启动，讲订单标识为已经启动状态
                            DB::table("order")->where("id",$device["order_id"])->update(["order_status_change"=>2,"back_pay_time"=>time()]);

                        }
                    }


                    $update["ins_gz"]=1;
                    $update["dev_status_name"]="工作中";
                    $update["run_time"]=hexdec($tm);//计算设备运行剩余时间
                }else if($status2==1){
                    //工作结束
                    $order= DB::table("order")->where(["id"=>$device["order_id"]])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                        }
                    }

                    $update["ins_gz"]=3;
                    $update["dev_status_name"]="工作完成";
                    //$update['order_id']=0;
                    $update["run_time"]=hexdec($tm);//计算设备运行剩余时间

                }else if($status2==7){

                    $update["dev_status_name"]="异常";
                    //$update['order_id']=0;
                    $update["run_time"]=hexdec($tm);//计算设备运行剩余时间

                }
                if($status3==4){
                    $update["dev_status_name"]="门盖打开";
                }

            }

            //判断设备是否上传经纬度
            if(array_key_exists("Lng",$receive_data)&&array_key_exists("Lat",$receive_data)){
                $lng=$receive_data["Lng"];//经度
                $lat=$receive_data["Lat"];//维度
                $update["dev_latitude"]=$lat;
                $update["dev_longitude"]=$lng;

            }

        }

        if(array_key_exists("sta",$data_arr['data'])){
            if($data_arr['data']['sta']==0){
                $update['ins_gz']=2;
                $update['dev_status_name']="通讯异常";
            }

        }
        $update['update_time']=time();


        DB::table("device")->where(["mqtt_name"=>$deviceName])->update($update);
    }


    public function  handleKbWasher4G($data_arr,$device)
    {
        //添加日志信息
        $this->addLog($data_arr, $device);
        $update = [];
        $update["sum_line"] = 1;//洗衣机模式
        //获取阿里云设备注册名称
        $deviceName=$data_arr['data']["deviceName"];
        //$device = M("device")->where(["mqtt_name" => $deviceName])->find();
        if (!$device) {
            return;//设备信息不存在就不用玩了
        }
        DB::table("device")->where(["dev_sim" => $device['dev_sim'], "dev_tp" => 7])->update(["ins_gz" => 4, "dev_status_name" => "设备离线"]);
        if (array_key_exists("sg", $data_arr)) {
            $update["signal"] = $data_arr['sg'] . "/" . date("Y-m-d H:i:s");
        }
        if(array_key_exists("ver",$data_arr['data'])){
            $update['ver']=$data_arr['data']['ver'];
        }

        if (array_key_exists("data", $data_arr)) {
            $receive_data = $data_arr["data"];
            if (!is_array($receive_data)) {
                $receive_data = json_decode($receive_data, true);
            }


            //判断设备的运行过程
            if(array_key_exists("mec",$receive_data)){
                $MecDat=$receive_data["mec"];
                $MecDat_arr=$this->getByateArray($MecDat,2);

                //运行状态	运行过程	程序选择	剩余时间	版本
                //1	           1	  1	      1	     1
                //00H~FFH	00H~FFH	00H~04H	00H~FFH	00H~99H
                //
                //运行状态
                //00H	空闲
                //01H	准备中
                //02H	正常工作中
                //03H	工作结束
                //04H	进水超时
                //05H	排水超时
                //06H	脱水异常
                //07H	脱水开盖
                //08H	水位异常
                //运行过程
                //00H	待机
                //01H	浸泡
                //02H	洗涤
                //03H	漂洗
                //04H	脱水
                //05H	消毒
                //06H	洁桶
                //07H	预留
                //08H	预留
                //09H	运行结束
                $status = $MecDat_arr[1];//运行状态
                $run_status = $MecDat_arr[2];//运行过程
                $command = $MecDat_arr[3]; //程序选择
                $run_time = hexdec($MecDat_arr[4]); //剩余时间
                $version = $MecDat_arr[5]; //版本
//var_dump($MecDat_arr);
                $update['ver'] =  $version;

                if($status==0){
                    $update['dev_status_name']="空闲";
                    if($run_time>0 && $run_status>0){
                        $update['dev_status_name']="工作中(可能门盖未关)";
                    }

                    //10/13 --lihaiqiang
                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            //10/20
                            DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            $update["order_id"]=0;

                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }
                    }

                }else if($status==1) {
                    $update["dev_status_name"] = "准备中";
                }else if($status==2){

                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-start-'.$run_process_status.json_encode($order)."\r\n",FILE_APPEND);

                        if($order_status_change==1){
                            //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-order_status_change-'.$order_status_change."\r\n",FILE_APPEND);

                            //确保当前订单已经付款成功过,设备成功启动，讲订单标识为已经启动状态
                            DB::table("order")->where("id",$device["order_id"])->update(["order_status_change"=>2,"back_pay_time"=>time()]);

                        }
                    }

                    $update["dev_status_name"]="正常工作中";
                }else if($status==3){
                    //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-end-'.$run_process_status.json_encode($device)."\r\n",FILE_APPEND);

                    $update["dev_status_name"]="工作结束";
                    $update['ins_gz']=3;
                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            $res = DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            //                     if($res){
                            //                         $api = new WechatController();
                            //                            $user = M('user')->find($order['user_id']);
                            //                         $api->send_msg($user['openid'],1,$order['id']);
                            //                     }
                            $update["order_id"]=0;
                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }
                    }



                }else if($status==4){
                    $update["dev_status_name"]="进水超时";
                }else if($status==5){
                    $update["dev_status_name"]="排水超时";
                }else if($status==6){
                    $update["dev_status_name"]="脱水异常";
                }else if($status==7){
                    $update["dev_status_name"]="脱水开盖";
                }else if($status==8){
                    $update["dev_status_name"]="水位异常";
                }
                $update["run_time"]=$run_time;
                if($run_status==0){
                    $update['dev_status']="待机";
                    $update['ins_gz']=3;
                }else if($run_status==1) {
                    $update["dev_status"] = "浸泡";
                    $update['ins_gz']=1;
                }else if($run_status==2){
                    $update["dev_status"]="洗涤";
                    $update['ins_gz']=1;
                }else if($run_status==3){
                    $update["dev_status"]="漂洗";
                    $update['ins_gz']=1;
                }else if($run_status==4){
                    $update["dev_status"]="脱水";
                    $update['ins_gz']=1;
                }else if($run_status==5){
                    $update["dev_status"]="消毒";
                    $update['ins_gz']=1;
                }else if($run_status==6){
                    $update["dev_status"]="洁桶";
                    $update['ins_gz']=1;
                }else if($run_status==7){
                    $update["dev_status"]="-";
                }else if($run_status==8){
                    $update["dev_status"]="-";
                } else if($run_status==9){
                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    $order_status_change=$order->order_status_change;
                    if($order){
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }

                        $update["order_id"]=0;
                    }
                    $update["dev_status"]="工作结束";
                    $update['ins_gz']=3;

                }
            }

            if($update['dev_status_name']=="正常工作中"&&$update["dev_status"]=="洁桶"){
                $update['dev_status_name']="桶自洁工作中";
            }
            //判断设备是否上传经纬度
            if (array_key_exists("Lng", $receive_data) && array_key_exists("Lat", $receive_data)) {
                $lng = $receive_data["Lng"];//经度
                $lat = $receive_data["Lat"];//维度
                $update["dev_latitude"] = $lat;
                $update["dev_longitude"] = $lng;

            }

        }
        if(array_key_exists("sta",$data_arr['data'])){
            if($data_arr['data']['sta']==0){
                $update['ins_gz']=4;
                $update['dev_status_name']="通讯异常";
            }


        }
        $update['update_time'] = time();
        //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-update-'.$tm.json_encode($update)."\r\n",FILE_APPEND);

        DB::table("device")->where("mqtt_name" , $deviceName)->update($update);
    }

    public function  handleDryer4G1($data_arr,$device){

        //step1:添加日志信息
        $this->addLog($data_arr,$device);
        //step2:解析上报数据信息
        $update=[];
        $update["sum_line"]=2;//烘干机模式
        //获取阿里云设备注册名称
        $deviceName=$data_arr["deviceName"];

        if(!$device){
            return ;//设备信息不存在就不用玩了
        }
        if(array_key_exists("sg",$data_arr)){
            $update["signal"]=$data_arr['sg']."/".date("Y-m-d H:i:s",time());
        }
        if(array_key_exists("data",$data_arr)){
            $receive_data=$data_arr["data"];
            if(!is_array($receive_data)){
                $receive_data=json_decode($receive_data,true);
            }
            if(array_key_exists("MecDat",$receive_data)){
                $MecDat=$receive_data["MecDat"];
                $MecDat_arr=$this->getByateArray($MecDat,2);
                if(strlen($MecDat)!=12||$MecDat_arr[0]!="0x"){
                    return ;
                }
                $Soft=hexdec($MecDat_arr[1]);//获取设备的工作状态
                //特殊状态指示
                $special_status=hexdec($MecDat_arr[2]);
                $version=$MecDat_arr[5];//程序的版本号码
                if($version){
                    $update["version"]=$version;
                }

                if($special_status&0x01){
                    //计算bit0 =1的情况
                    $update["wind1"]="按键已锁";
                }else{
                    $update["wind1"]="按键未锁";
                }
                if($special_status&0x02){
                    //计算bit1=1 的情况
                    $update['wind2']="启动智能判断";
                }else{
                    $update['wind2']="未启动智能判断";
                }
                if($Soft==1){
                    $update["ins_gz"]=3;
                    $update["dev_status_name"]="准备中";
                    $update["run_time"]=hexdec($MecDat_arr[3].$MecDat_arr[4]);//计算设备运行剩余时间
                }else if($Soft==2){
                    $order=Db::table("order")->where(["id"=>$device["order_id"]])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==1){
                            //确保当前订单已经付款成功过,设备成功启动，讲订单标识为已经启动状态
                            Db::table("order")->where(["id"=>$device["order_id"]])->update(["order_status_change"=>2,"back_pay_time"=>time()]);

                        }
                    }

                    $update["ins_gz"]=1;
                    $update["dev_status_name"]="工作中";
                    $update["run_time"]=hexdec($MecDat_arr[3].$MecDat_arr[4]);//计算设备运行剩余时间
                }else if($Soft==3||$Soft==0){
                    //工作结束
                    $order=Db::table("order")->where(["id"=>$device["order_id"]])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            Db::table("order")->where(["id"=>$device['order_id']])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                        }
                        $update['order_id']=0;
                    }

                    $update["ins_gz"]=3;
                    $update["dev_status_name"]="工作完成";

                    $update["run_time"]=hexdec($MecDat_arr[3].$MecDat_arr[4]);//计算设备运行剩余时间

                }else if($Soft==4){
                    $update["ins_gz"]=4;
                    $update["dev_status_name"]="设备离线";
                }else if($Soft==5){
                    //上传温湿度值
                    $update["temperature"]=hexdec($MecDat_arr[3]);
                    $update["humidity"]=hexdec($MecDat_arr[4]);
                }else if($Soft==10){
                    $update["dev_status_name"]="温度传感器失效";
                    $update['ins_gz']=2;
                }else if($Soft==11){
                    $update["dev_status_name"]="湿度传感器失效";
                    $update['ins_gz']=2;
                }else if($Soft==12) {
                    $update["dev_status_name"] = "温度湿度传感器同时故障";
                    $update['ins_gz']=2;
                }else if($Soft==13){
                    $update["dev_status_name"]="工作状态时开门被打开";
                    $update['ins_gz']=2;
                }else if($Soft==35){
                    $update["dev_status_name"]="待机时门被打开";
                    $update['ins_gz']=3;
                }else if($Soft==128){
                    $update['dev_status_name']="桶自洁工作中";
                    $update['ins_gz']=1;
                }else if($Soft==129){
                    $update["dev_status_name"]="掉电自动工作中";
                    $update['ins_gz']=1;
                }
            }

            //判断设备是否上传经纬度
            if(array_key_exists("Lng",$receive_data)&&array_key_exists("Lat",$receive_data)){
                $lng=$receive_data["Lng"];//经度
                $lat=$receive_data["Lat"];//维度
                $update["dev_latitude"]=$lat;
                $update["dev_longitude"]=$lng;

            }
            if(array_key_exists("ver",$receive_data)){ //硬件程序版本
                $update["version"] = $receive_data['ver'];
            }
            if(array_key_exists("pro_ver",$receive_data)){ //通讯板软件版
                $update["ver"] = $receive_data['pro_ver'];
            }

        }
        $update['update_time']=time();
        Db::table("device")->where(["mqtt_name"=>$deviceName])->update($update);
    }
    public function  handleNewKbWasher4G($data_arr,$device)
    {
        //添加日志信息
        $this->addLog($data_arr, $device);
        $update = [];
        $update["sum_line"] = 1;//洗衣机模式
        //获取阿里云设备注册名称
        $deviceName=$data_arr['data']["deviceName"];

        if (!$device) {
            return;//设备信息不存在就不用玩了
        }
        DB::table("device")->where(["dev_sim" => $device['dev_sim'], "dev_tp" => 7])->update(["ins_gz" => 4, "dev_status_name" => "设备离线"]);
        if (array_key_exists("sg", $data_arr)) {
            $update["signal"] = $data_arr['sg'] . "/" . date("Y-m-d H:i:s", time());
        }
        if(array_key_exists("ver",$data_arr['data'])){//通讯板软件版本
            $update['ver']=$data_arr['data']['ver'];
        }
        if (array_key_exists("data", $data_arr)) {
            $receive_data = $data_arr["data"];
            if (!is_array($receive_data)) {
                $receive_data = json_decode($receive_data, true);
            }

            //判断设备的运行过程
            if(array_key_exists("sta",$receive_data)&&array_key_exists("tm",$receive_data)&&array_key_exists("rn",$receive_data)){
                $run_process_status=$receive_data["sta"];//设备工作状态
                $tm=$receive_data['tm'];//剩余运行时间
                $run_status=$receive_data["rn"];//运行过程

                if($run_process_status==0){
                    $update['dev_status_name']="空闲";
                    if($tm>0 && $run_status>0){
                        $update['dev_status_name']="工作中(可能门盖未关)";
                    }
                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            //10/20
                            DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            $update["order_id"]=0;

                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }
                    }

                }else if($run_process_status==1) {
                    $update["dev_status_name"] = "准备中";
                }else if($run_process_status==2){

                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-start-'.$run_process_status.json_encode($order)."\r\n",FILE_APPEND);

                        if($order_status_change==1){
                            //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-order_status_change-'.$order_status_change."\r\n",FILE_APPEND);

                            //确保当前订单已经付款成功过,设备成功启动，讲订单标识为已经启动状态
                            DB::table("order")->where("id",$device["order_id"])->update(["order_status_change"=>2,"back_pay_time"=>time()]);

                        }
                    }

                    $update["dev_status_name"]="正常工作中";

                }else if($run_process_status==3){
                    //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-end-'.$run_process_status.json_encode($device)."\r\n",FILE_APPEND);
                    $update["dev_status_name"]="工作结束";
                    $update['ins_gz']=3;
                    $order=DB::table("order")->where("id",$device["order_id"])->first();
                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            $res = DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            //                     if($res){
                            //                         $api = new WechatController();
                            //                            $user = M('user')->find($order['user_id']);
                            //                         $api->send_msg($user['openid'],1,$order['id']);
                            //                     }
                            $update["order_id"]=0;
                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }
                    }

                }else if($run_process_status==4){
                    $update["dev_status_name"]="进水超时";
                }else if($run_process_status==5){
                    $update["dev_status_name"]="排水超时";
                }else if($run_process_status==6){
                    $update["dev_status_name"]="脱水异常";
                }else if($run_process_status==7){
                    $update["dev_status_name"]="脱水开盖";
                }else if($run_process_status==8){
                    $update["dev_status_name"]="水位异常";
                }else if($run_process_status==9){
                    $update["dev_status_name"]="指令未执行";
                }else if($run_process_status==10){
                    $update["dev_status_name"]="失去连接";
                }
                $update["run_time"]=$tm;
                if($run_status==0){
                    $update['dev_status']="待机";
                    $update['ins_gz']=3;
                }else if($run_status==1) {
                    $update["dev_status"] = "浸泡";
                    $update['ins_gz']=1;
                }else if($run_status==2){
                    $update["dev_status"]="洗涤";
                    $update['ins_gz']=1;
                }else if($run_status==3){
                    $update["dev_status"]="漂洗";
                    $update['ins_gz']=1;
                }else if($run_status==4){
                    $update["dev_status"]="脱水";
                    $update['ins_gz']=1;
                }else if($run_status==5){
                    $update["dev_status"]="消毒";
                    $update['ins_gz']=1;
                }else if($run_status==6){
                    $update["dev_status"]="洁桶";
                    $update['ins_gz']=1;
                }else if($run_status==7){
                    $update["dev_status"]="-";
                }else if($run_status==8){
                    $update["dev_status"]="-";
                } else if($run_status==9){

                    $order=DB::table("order")->where("id",$device["order_id"])->first();

                    if($order){
                        $order_status_change=$order->order_status_change;
                        if($order_status_change==2){ //设备正常工作过,讲订单标为已完成
                            //已经付款
                            //人为判断标识机器状态为工作中
                            DB::table("order")->where("id",$device['order_id'])->update(["order_status_change"=>3,"type"=>2,"back_pay"=>1]);
                            $update["end_time"]=date("Y-m-d H:i:s",time());//机器完成时间
                        }

                        $update["order_id"]=0;
                    }
                    $update["dev_status"]="工作结束";
                    $update['ins_gz']=3;

                }
            }
            if(array_key_exists("ver",$receive_data)){ //硬件程序版本
                $update["version"] = $receive_data['ver'];
            }
            if(array_key_exists("pro_ver",$receive_data)){ //通讯板软件版
                $update["ver"] = $receive_data['pro_ver'];
            }
            if($update['dev_status_name']=="正常工作中"&&$update["dev_status"]=="洁桶"){
                $update['dev_status_name']="桶自洁工作中";
            }
            //判断设备是否上传经纬度
            if (array_key_exists("Lng", $receive_data) && array_key_exists("Lat", $receive_data)) {
                $lng = $receive_data["Lng"];//经度
                $lat = $receive_data["Lat"];//维度
                $update["dev_latitude"] = $lat;
                $update["dev_longitude"] = $lng;

            }

        }
        $update['update_time'] = time();
        $update['dev_tp'] = 11;
        //file_put_contents("/home/wwwroot/apps/exilesystem/Application/Runtime/kb.log",date("Y-m-d H:i:s").'-update-'.$tm.json_encode($update)."\r\n",FILE_APPEND);

        DB::table("device")->where("mqtt_name" , $deviceName)->update($update);
    }

    protected  function  addLog($data_arr,$device){
        if($device&&$data_arr){
            $insert = array();
            $insert['msg']=json_encode($data_arr);
            $insert['data']=json_encode($data_arr);
            $insert['mqtt_name']=$device['mqtt_name'];
            $insert['create_time']=time();
            if($device['dev_type']){
                $insert['device_type']=$device['dev_type'];
            }

            if($device['dev_code']){
                $insert['device_code']=$device['dev_code'];
            }

            if($device['agent_id']){
                $insert['agent_id']=$device['agent_id'];
            }

            if($device['id']){
                $insert['device_id']=$device['id'];
            }


            DB::table("mqtt_msg")->insert($insert);
        }
    }



    public  function  getByateArray($str,$step){
        $str_len = strlen($str);
        $ret = array(); // 最终返回的数组
        for ($i=0; $i<$str_len; $i+=$step) {
            if(strlen($str) >= $step) {
                $ret[] = substr($str, 0, $step);
                $str = substr($str, $step);
            }else {
                $ret[] = $str;
            }
        }
        return $ret;
    }


    public function publish($command,$deviceName,$type){

        $data = ["cmd"=>"0x0".$command];

        if($command == "changemode-0"){//切换到洗衣机
            $data = ["changemode"=>0];
        }
        if($command == "changemode-1"){//切换到烘干机
            $data = ["changemode"=>1];
        }
        if($command == "pro-50001"){//查询iemi
            $data = ["pro"=>50001];
        }

        if($command == "pro-50002"){//查询sim卡号
            $data = ["pro"=>50002];
        }
        $server = 'emqx.hmahm.cn';     // change if necessary
        $port = 1883;                     // change if necessary
        $username = 'lhq';                   // set your username
        $password = '123456';                   // set your password
        $client_id = 'test'; // make sure this is unique for connecting to sever - you could use uniqid()


        if($type == 1){//洗衣机
            $topic = "/iot/Washer/sub/".$deviceName;
        }
        if($type == 2){//烘干机
            $topic = "/iot/Dryer/sub/".$deviceName;
        }

        $mqtt = new Publish($server, $port, $client_id);

        if ($mqtt->connect(true, NULL, $username, $password)) {

            $mqtt->publish($topic, json_encode($data));

            $mqtt->close();
        } else {
            echo "Time out!\n";
        }
    }




























}